package org.frogs.algo;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Utilities {

	public static void main(String[] args) throws FileNotFoundException {
		
		
		File testFile = new File("D:/Projects/GoogleCode/PC Magazine Contest 2012-2013/Frogmagedon/tests/test.txt");
		Scanner scanner = new Scanner(testFile);
		
		FrogPool gameField = new FrogPool(scanner);
		
		Player.play(gameField);
		/*
		Point2 p1 = new Point2(5.0, 5.0);
		Point2 p2 = new Point2(2.0, 3.0);
		Point2 p3 = new Point2(-1.0, -10.0);
		System.out.println(Utilities.pointToLineDistance(p1,p2, p3));
		*/
	}
	
	public static Point2 avoidBullet(Frog frog, Bullet bullet) {
		Point2 frogCenter = new Point2(frog.getCenterX(), frog.getCenterY());
		
		double distanceToBullet = getFrogToBulletLineDistance(frog, bullet);
		//System.out.println("distance to bullet path: " + distanceToBullet);
		Point2 direction;
		
		//Sign of the distance
		int signDistance = -1;
		if (distanceToBullet < 0) {
			signDistance = 1;
		}
		
		//System.out.println("moving away...");
		direction = Point2.normal(bullet.getCurrentX(), bullet.getCurrentY(),
				bullet.getNextX(), bullet.getNextY());
		
		return moveToDirection(frogCenter, direction, 2*signDistance);
	}
	
	public static Point2 moveToDirection(Point2 point, Point2 direction, double distance) {
		Point2 newDirection = new Point2(direction);
		
		newDirection.x = newDirection.x/Point2.Magnitude(newDirection);
		newDirection.y = newDirection.y/Point2.Magnitude(newDirection);
		
		newDirection = Point2.multiplyByCoef(newDirection, distance);
		
		return Point2.SumVectors(point, newDirection);
		
	}

	public static double getFrogToBulletLineDistance(Frog frog, Bullet bullet) {
		return getPointToBulletDistance(frog.centerPoint, bullet);
	}
	
	public static double getPointToBulletDistance(Point2 point, Bullet bullet) {
		if (bullet == null || Point2.getDistanceBetweenPoints(point, bullet.currentPoint) > 35) {
			return 100;
		}
		
		return pointToLineDistance(
				new Point2(bullet.getCurrentX(), bullet.getCurrentY()),
				new Point2(bullet.getNextX(), bullet.getNextY()),
				point);
	}
	
	public static double pointToLineDistance(Point2 A, Point2 B, Point2 P) {
	    //double normalLength = Math.sqrt((B.x-A.x)*(B.x-A.x)+(B.y-A.y)*(B.y-A.y));
	    //return (P.x-A.x)*(B.y-A.y)-(P.y-A.y)*(B.x-A.x)/normalLength;+
		return ((A.x - B.x)*(B.y - P.y) - (B.x - P.x)*(A.y - B.y))/(Math.sqrt((A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y)));
	}
	
	public static double pointToPointDistance(Point2 A, Point2 B) {
		return Math.sqrt(((A.x - B.x)*(A.x - B.x))+((A.y - B.y)*(A.y - B.y)));
	}
}
